/*
 * @Description: * 网络请求封装
 * @Date: 2020-08-26 15:56:20
 * @LastEditTime: 2020-08-26 18:18:42
 * @Author: SBD
 * @FilePath: /cms/src/utils/request.js
 */

import axios from 'axios'
import {
  Message
} from 'element-ui'
// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // 跨域请求时发送Cookie
  timeout: 30000 // 请求超时
})
console.log(process.env.VUE_APP_BASE_API);
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做一些事情
    config.headers.token = localStorage.getItem('token')
    return config
  },
  error => {
    // 做一些请求错误
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // 如果自定义代码不是100，则将其判断为错误。
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error check your token or method',
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service.request
